class Calendar {
    constructor() {
        this.today = new Date();
        this.notes = {};
        this.currentDate = null;
        this.init();
    }

    async init() {
        await this.loadNotes();
        await this.renderCalendar();
        this.setupEventListeners();
    }

    async loadNotes() {
        try {
            const response = await fetch('/api/notes');
            this.notes = await response.json();
        } catch (error) {
            console.error('加载备注失败:', error);
        }
    }

    async renderCalendar() {
        const months = [
            "January", "February", "March", "April",
            "May", "June", "July", "August",
            "September", "October", "November", "December"
        ];
        const calendarDiv = document.getElementById('calendar');
        const monthGrid = document.createElement('div');
        monthGrid.className = 'month-grid';

        for (let i = 0; i < months.length; i++) {
            const monthDiv = await this.createMonth(months[i], i);
            monthGrid.appendChild(monthDiv);
        }

        calendarDiv.appendChild(monthGrid);
    }

    async createMonth(monthName, monthIndex) {
        const monthDiv = document.createElement('div');
        monthDiv.className = 'month';

        // 月份标题
        const header = document.createElement('div');
        header.className = 'month-header';
        header.innerHTML = `
            <span>${monthIndex + 1}月</span>
            <span>${monthName}</span>
        `;
        monthDiv.appendChild(header);

        // 星期标题
        const weekdaysDiv = document.createElement('div');
        weekdaysDiv.className = 'weekdays';
        // 直接使用简化的星期显示
        const simpleDays = ['日', '一', '二', '三', '四', '五', '六'];
        simpleDays.forEach(day => {
            weekdaysDiv.innerHTML += `<div>${day}</div>`;
        });
        monthDiv.appendChild(weekdaysDiv);

        // 日期
        const daysDiv = document.createElement('div');
        daysDiv.className = 'days';
        
        const firstDay = new Date(2025, monthIndex, 1).getDay();
        const daysInMonth = new Date(2025, monthIndex + 1, 0).getDate();

        // 添加空白天数
        for (let i = 0; i < firstDay; i++) {
            daysDiv.innerHTML += '<div class="day"></div>';
        }

        // 添加日期
        for (let day = 1; day <= daysInMonth; day++) {
            const date = `2025-${(monthIndex + 1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
            const dateObj = new Date(2025, monthIndex, day);
            const note = this.notes[date];
            const isWeekend = (firstDay + day - 1) % 7 === 6 || (firstDay + day - 1) % 7 === 0;
            
            // 检查是否是今天
            const isToday = this.today.getDate() === day && 
                           this.today.getMonth() === monthIndex && 
                           this.today.getFullYear() === 2025;
            
            const weekNumber = this.getWeekNumber(dateObj);
            const dayOfYear = this.getDayOfYear(dateObj);
            
            const dayDiv = document.createElement('div');
            dayDiv.className = `day${isWeekend ? ' weekend' : ''}${isToday ? ' today' : ''}`;
            dayDiv.innerHTML = day;
            dayDiv.setAttribute('data-date', date);
            
            // 更新提示文本，移除农历显示
            const tooltip = [
                `2025年第${dayOfYear}天`,
                `2025年第${weekNumber}周`,
                note?.text ? `备注：${note.text}` : null
            ].filter(Boolean).join('\n');
            
            dayDiv.setAttribute('title', tooltip);
            
            if (note) {
                dayDiv.style.backgroundColor = note.bgColor || '';
                if (note.text) {
                    const indicator = document.createElement('div');
                    indicator.className = 'note-indicator';
                    dayDiv.appendChild(indicator);
                }
            }

            dayDiv.addEventListener('click', (e) => this.openModal(date));
            daysDiv.appendChild(dayDiv);
        }

        monthDiv.appendChild(daysDiv);
        return monthDiv;
    }

    // 暂时返回空字符串
    async getLunarDate(date) {
        return '';
    }

    setupEventListeners() {
        const modal = document.getElementById('noteModal');
        const closeBtn = document.querySelector('.close');
        const saveBtn = document.getElementById('saveNote');
        const deleteBtn = document.getElementById('deleteNote');

        closeBtn.onclick = () => modal.style.display = 'none';
        window.onclick = (e) => {
            if (e.target === modal) modal.style.display = 'none';
        }
        saveBtn.onclick = () => this.saveNote();
        deleteBtn.onclick = () => this.deleteNote();
    }

    openModal(date) {
        this.currentDate = date;
        const modal = document.getElementById('noteModal');
        const noteText = document.getElementById('noteText');
        const bgColor = document.getElementById('bgColor');
        const deleteBtn = document.getElementById('deleteNote');

        const note = this.notes[date] || { text: '', bgColor: '#ffffff' };
        noteText.value = note.text;
        bgColor.value = note.bgColor || '#ffffff';

        // 如果没有备注，隐藏删除按钮
        deleteBtn.style.display = note.text || note.bgColor !== '#ffffff' ? 'block' : 'none';

        modal.style.display = 'block';
    }

    async saveNote() {
        const noteText = document.getElementById('noteText').value;
        const bgColor = document.getElementById('bgColor').value;
        
        try {
            await fetch('/api/notes', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    date: this.currentDate,
                    note: { text: noteText, bgColor }
                })
            });

            this.notes[this.currentDate] = { text: noteText, bgColor };
            this.updateDayDisplay(this.currentDate);
            document.getElementById('noteModal').style.display = 'none';
        } catch (error) {
            alert('保存失败，请稍后重试');
        }
    }

    updateDayDisplay(date) {
        const dayElement = document.querySelector(`[data-date="${date}"]`);
        if (dayElement) {
            const note = this.notes[date];
            dayElement.style.backgroundColor = note.bgColor;
            
            let indicator = dayElement.querySelector('.note-indicator');
            if (note.text && !indicator) {
                indicator = document.createElement('div');
                indicator.className = 'note-indicator';
                dayElement.appendChild(indicator);
            } else if (!note.text && indicator) {
                indicator.remove();
            }
        }
    }

    // 添加获取年度周数的方法
    getWeekNumber(date) {
        const target = new Date(date);
        const firstDayOfYear = new Date(target.getFullYear(), 0, 1);
        const days = Math.floor((target - firstDayOfYear) / (24 * 60 * 60 * 1000));
        return Math.ceil((days + firstDayOfYear.getDay() + 1) / 7);
    }

    // 添加获取年度天数的方法
    getDayOfYear(date) {
        const start = new Date(date.getFullYear(), 0, 0);
        const diff = date - start;
        const oneDay = 1000 * 60 * 60 * 24;
        return Math.floor(diff / oneDay);
    }

    async deleteNote() {
        if (!confirm('确定要删除这条备注吗？')) {
            return;
        }

        try {
            await fetch('/api/notes', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    date: this.currentDate
                })
            });

            // 删除本地数据
            delete this.notes[this.currentDate];
            
            // 更新显示
            const dayElement = document.querySelector(`[data-date="${this.currentDate}"]`);
            if (dayElement) {
                dayElement.style.backgroundColor = '';
                const indicator = dayElement.querySelector('.note-indicator');
                if (indicator) {
                    indicator.remove();
                }
            }

            document.getElementById('noteModal').style.display = 'none';
        } catch (error) {
            alert('删除失败，请稍后重试');
        }
    }
}

// 初始化日历
document.addEventListener('DOMContentLoaded', () => {
    new Calendar();
}); 